# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def __init__(self):
        self.current = TreeNode()

    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: Optional[TreeNode]
        """
        self.loop(preorder, inorder, self.current)
        return self.current

    def loop(self, preorder, inorder, current):
        current.val = preorder[0]
        index = inorder.index(preorder[0])

        preorder_left = preorder[1:index + 1]
        preorder_right = preorder[index + 1:]
        inorder_left = inorder[:index]
        inorder_right = inorder[index + 1:]

        if preorder_left:
            current.left = TreeNode()
            self.loop(preorder_left, inorder_left, current.left)

        if preorder_right:
            current.right = TreeNode()
            self.loop(preorder_right, inorder_right, current.right)



